package com.yunwaikeji.gy_tool_library.widget;

import android.animation.ArgbEvaluator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

import com.yunwaikeji.gy_tool_library.R;
import com.yunwaikeji.gy_tool_library.adapter.GYFragmentPagerAdapter;
import com.yunwaikeji.gy_tool_library.model.GYBottomBarModel;
import com.yunwaikeji.gy_tool_library.info.GYBottomBarInfo;
import com.yunwaikeji.gy_tool_library.utils.display.GYDisplayUtils;
import com.yunwaikeji.gy_tool_library.view.GYImageView;
import com.yunwaikeji.gy_tool_library.view.GYLinearLayout;
import com.yunwaikeji.gy_tool_library.view.GYTextView;
import com.yunwaikeji.gy_tool_library.view.GYView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class GYBottomBar extends GYLinearLayout implements GYBottomBarInfo {
    public GYBottomBar(Context context) {
        this(context, null);
    }

    public GYBottomBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GYBottomBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public GYBottomBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(attrs);
    }

    private int contentBackgroundColor = Color.TRANSPARENT;
    private int bottomHeightPx = GYDisplayUtils.dp2px(getContext(), 40);
    //    private int bottomBackgroundColor = Color.TRANSPARENT;
    private int bottomRadius = 0;
    private int tabPressColor = WRAP_CONTENT;
    private int tabTextImageSpacingPx = 0;
    private int tabShowType = TabShowType.VERTICAL_IMAGE_TEXT;
    private boolean tabShowPass = false;//tab是否显示经过路径
    private boolean tabShowAnimation = true;//tab是否显示动画
    private int tabTextSizePx = GYDisplayUtils.sp2px(getContext(), 14);
    private int tabImageWidthPx = GYDisplayUtils.dp2px(getContext(), 24);
    private int tabImageHeightPx = GYDisplayUtils.dp2px(getContext(), 24);
    private int tabTextNormalColor = Color.LTGRAY;
    private int tabTextSelectColor = Color.BLACK;

    private GYViewPager bottomBarViewPager;
    //    private GYRecyclerView bottomBarRecyclerView;
    private GYView dividerView;
    private GYLinearLayout bottomBarLL;

    private List<Fragment> fragmentList = new ArrayList<>();
    private List<GYBottomBarModel> gyBottomBarBeanList = new ArrayList<>();

    private GYFragmentPagerAdapter gyFragmentPagerAdapter;
//    private GYFragmentAdapter gyFragmentAdapter;

    private void init(AttributeSet attributeSet) {
        LayoutInflater.from(getContext()).inflate(R.layout.view_bottom_bar, this);
        bottomBarViewPager = findViewById(R.id.bottomBarViewPager);
//        bottomBarRecyclerView = findViewById(R.id.bottomBarRecyclerView);
        dividerView = findViewById(R.id.dividerView);
        bottomBarLL = findViewById(R.id.bottomBarLL);
        if (attributeSet != null) {
            TypedArray typedArray = getContext().obtainStyledAttributes(attributeSet, R.styleable.GYBottomBar);
            contentBackgroundColor = typedArray.getColor(R.styleable.GYBottomBar_contentBackgroundColor, contentBackgroundColor);
            bottomHeightPx = typedArray.getDimensionPixelSize(R.styleable.GYBottomBar_bottomHeight, bottomHeightPx);
            int bottomBackgroundColor = typedArray.getColor(R.styleable.GYBottomBar_bottomBackgroundColor, Color.TRANSPARENT);
            setBottomBackgroundColor(bottomBackgroundColor);
            bottomRadius = typedArray.getDimensionPixelSize(R.styleable.GYBottomBar_bottomRadius, bottomRadius);
            tabPressColor = typedArray.getColor(R.styleable.GYBottomBar_tabClickColor, tabPressColor);
            tabTextImageSpacingPx = typedArray.getDimensionPixelSize(R.styleable.GYBottomBar_tabTextImagePadding, tabTextImageSpacingPx);
            tabShowType = typedArray.getInteger(R.styleable.GYBottomBar_tabShowType, tabShowType);
            boolean pagerScroll = typedArray.getBoolean(R.styleable.GYBottomBar_pagerScroll, true);//pager是否可以滑动
            boolean pagerShowAnimation = typedArray.getBoolean(R.styleable.GYBottomBar_pagerShowAnimation, true);//pager是否显示滑动动画
            tabShowPass = typedArray.getBoolean(R.styleable.GYBottomBar_tabShowPass, tabShowPass);
            tabShowAnimation = typedArray.getBoolean(R.styleable.GYBottomBar_tabShowAnimation, tabShowAnimation);
            tabTextSizePx = typedArray.getDimensionPixelSize(R.styleable.GYBottomBar_tabTextSize, tabTextSizePx);
            tabImageWidthPx = typedArray.getDimensionPixelSize(R.styleable.GYBottomBar_tabImageWidth, tabImageWidthPx);
            tabImageHeightPx = typedArray.getDimensionPixelSize(R.styleable.GYBottomBar_tabImageHeight, tabImageHeightPx);
            int dividerHeightPx = typedArray.getDimensionPixelSize(R.styleable.GYBottomBar_dividerHeight, 0);
            int dividerColor = typedArray.getColor(R.styleable.GYBottomBar_dividerColor, Color.LTGRAY);
            tabTextNormalColor = typedArray.getColor(R.styleable.GYBottomBar_tabTextNormalColor, tabTextNormalColor);
            tabTextSelectColor = typedArray.getColor(R.styleable.GYBottomBar_tabTextSelectColor, tabTextSelectColor);
            int offscreenPageLimit = typedArray.getInteger(R.styleable.GYBottomBar_offscreenPageLimit, WRAP_CONTENT);
            int overScrollMode = typedArray.getInteger(R.styleable.GYBottomBar_android_overScrollMode, OVER_SCROLL_NEVER);
            typedArray.recycle();
            setPagerScroll(pagerScroll);
            setPagerShowAnimation(pagerShowAnimation);
            setDividerHeightPx(dividerHeightPx);
            setDividerColor(dividerColor);
            setOverScrollMode1(overScrollMode);
            if (offscreenPageLimit != WRAP_CONTENT) {
                setOffscreenPageLimit(offscreenPageLimit);
            }
        }

        bottomBarViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (onPageChangeListener != null) {
                    onPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
                }
                setTabGradualChange(position, positionOffset);
            }

            @Override
            public void onPageSelected(int position) {
                if (onPageChangeListener != null) {
                    onPageChangeListener.onPageSelected(position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (onPageChangeListener != null) {
                    onPageChangeListener.onPageScrollStateChanged(state);
                }
                if (state == 0) {
                    isClick = false;
                }
            }
        });
        setBottomHeightPx(bottomHeightPx);
    }

    private ViewPager.OnPageChangeListener onPageChangeListener;

    public GYBottomBar setOnPageChangeListener(ViewPager.OnPageChangeListener onPageChangeListener) {
        this.onPageChangeListener = onPageChangeListener;
        return this;
    }

    public GYBottomBar setOverScrollMode1(int overScrollMode) {
        super.setOverScrollMode(overScrollMode);
        bottomBarViewPager.setOverScrollMode(overScrollMode);
//        bottomBarRecyclerView.setOverScrollMode(overScrollMode);
        return this;
    }

    public GYBottomBar setTabSelect(int position) {
        if (bottomBarLL.getViewSet().getChildViews().size() > 0) {
            for (int i = 0; i < bottomBarLL.getViewSet().getChildViews().size(); i++) {
                if (i == position) {
                    setTabTextViewColor(getTabTextView(i), tabTextSelectColor);
                    setTabImageTransform(getTabImageView(i), 1);
                } else {
                    setTabTextViewColor(getTabTextView(i), tabTextNormalColor);
                    setTabImageTransform(getTabImageView(i), 0);
                }
            }
        }
        return this;
    }

    public GYBottomBar setBottomBackgroundColor(int bottomBackgroundColor) {
        bottomBarLL.getBackgroundBuilder().setBackgroundColor(bottomBackgroundColor).build();
        return this;
    }

    public GYBottomBar setBottomHeightPx(int bottomHeightPx) {
        this.bottomHeightPx = bottomHeightPx;
        bottomBarLL.getViewSet().setHeightPx(bottomHeightPx);
        return this;
    }

    public GYBottomBar setBottomHeightDp(int bottomHeightDp) {
        return setBottomHeightPx(GYDisplayUtils.dp2px(getContext(), bottomHeightDp));
    }

    public GYBottomBar setOffscreenPageLimit(int limit) {
        bottomBarViewPager.setOffscreenPageLimit(limit);
        return this;
    }

    public GYBottomBar setDividerHeightPx(int dividerHeightPx) {
        dividerView.getViewSet().setHeightPx(dividerHeightPx);
        return this;
    }

    public GYBottomBar setDividerHeightDp(int dividerHeightDp) {
        dividerView.getViewSet().setHeightDp(dividerHeightDp);
        return this;
    }

    public GYBottomBar setDividerColor(int dividerColor) {
        dividerView.getBackgroundBuilder().setBackgroundColor(dividerColor).build();
        return this;
    }

    public GYBottomBar setTabs(GYBottomBarModel... gyBottomBarBeans) {
        return setTabs(Arrays.asList(gyBottomBarBeans));
    }

    public GYBottomBar setTabs(List<GYBottomBarModel> gyBottomBarBeanList) {
        this.gyBottomBarBeanList.clear();
        return addTabs(gyBottomBarBeanList);
    }

    public GYBottomBar addTabs(GYBottomBarModel... gyBottomBarBeans) {
        return addTabs(Arrays.asList(gyBottomBarBeans));
    }

    public GYBottomBar addTabs(List<GYBottomBarModel> gyBottomBarBeanList) {
        this.gyBottomBarBeanList.addAll(gyBottomBarBeanList);
        notifyDataSetChanged();
        return this;
    }

    public GYBottomBar setTabShowType(@TabShowType int tabShowType) {
        this.tabShowType = tabShowType;
        notifyDataSetChanged();
        return this;
    }

    public GYBottomBar setCurrentItem(int item) {
        bottomBarViewPager.setCurrentItem(item);
        return this;
    }

    public int getCurrentItem() {
        return bottomBarViewPager.getCurrentItem();
    }

    public GYBottomBar setPagerScroll(boolean pagerScroll) {
        bottomBarViewPager.setScroll(pagerScroll);
        return this;
    }

    public boolean isPagerScroll() {
        return bottomBarViewPager.isScroll();
    }

    public GYBottomBar setPagerShowAnimation(boolean pagerShowAnimation) {
        bottomBarViewPager.setShowAnimation(pagerShowAnimation);
        return this;
    }

    public boolean isPagerShowAnimation() {
        return bottomBarViewPager.isShowAnimation();
    }

    public GYBottomBar setTabShowPass(boolean tabShowPass) {
        this.tabShowPass = tabShowPass;
        return this;
    }

    public boolean isTabShowPass() {
        return tabShowPass;
    }

    public GYBottomBar setTabShowAnimation(boolean tabShowAnimation) {
        this.tabShowAnimation = tabShowAnimation;
        return this;
    }

    public boolean isTabShowAnimation() {
        return tabShowAnimation;
    }

    private int clickPosition;//点击的item
    private boolean isClick = false;//是否为点击的
    private int nowPosition = 0;

    public void notifyDataSetChanged() {
        bottomBarLL.removeAllViews();
        fragmentList.clear();
        for (int i = 0; i < gyBottomBarBeanList.size(); i++) {
            GYBottomBarModel gyBottomBarBean = gyBottomBarBeanList.get(i);
            int finalI = i;
            GYLinearLayout gyLinearLayout = new GYLinearLayout(getContext())
                    .getViewSet()
                    .setGravity(Gravity.CENTER)
                    .setOnClickListener(v -> {
                        clickPosition = finalI;
                        isClick = true;
                        nowPosition = bottomBarViewPager.getCurrentItem();
                        bottomBarViewPager.setCurrentItem(finalI);
                    })
                    .setSizePx(0, MATCH_PARENT, 1).toView();
            if (tabPressColor != WRAP_CONTENT) {
                gyLinearLayout.getBackgroundBuilder().setChangeColor(tabPressColor).build();
            }
            bottomBarLL.getViewSet().addViews(gyLinearLayout);
            GYTextView gyTextView = new GYTextView(getContext()).getViewSet().setGravity(Gravity.CENTER).toView();
            GYImageView gyImageView = new GYImageView(getContext()).getViewSet().setSizePx(tabImageWidthPx, tabImageHeightPx).toView();
            switch (tabShowType) {
                case TabShowType.VERTICAL_IMAGE_TEXT:
                    gyTextView.getViewSet().setText(gyBottomBarBean.getTitle())
                            .setWidthPx(MATCH_PARENT)
                            .setMarginPx(0, tabTextImageSpacingPx, 0, 0);
                    gyLinearLayout.getViewSet().setOrientation(LinearLayout.VERTICAL)
                            .addViews(gyImageView.getViewSet().setTransformImages(gyBottomBarBean.getNormalDrawable()
                                    , gyBottomBarBean.getSelectDrawable(), tabImageWidthPx, tabImageHeightPx).toView()
                                    , gyTextView);
                    break;
                case TabShowType.VERTICAL_TEXT_IMAGE:
                    gyTextView.getViewSet().setText(gyBottomBarBean.getTitle())
                            .setWidthPx(MATCH_PARENT);
                    gyLinearLayout.getViewSet().setOrientation(LinearLayout.VERTICAL)
                            .addViews(gyTextView,
                                    gyImageView.getViewSet().setTransformImages(gyBottomBarBean.getNormalDrawable(), gyBottomBarBean.getSelectDrawable(), tabImageWidthPx, tabImageHeightPx).toView()
                                            .getViewSet().setMarginPx(0, tabTextImageSpacingPx, 0, 0).toView());
                    break;
                case TabShowType.HORIZONTAL_IMAGE_TEXT:
                    gyTextView.getViewSet().setText(gyBottomBarBean.getTitle()).setMarginPx(0, tabTextImageSpacingPx, 0, 0);
                    gyLinearLayout.getViewSet().setOrientation(LinearLayout.HORIZONTAL)
                            .addViews(gyImageView.getViewSet().setTransformImages(gyBottomBarBean.getNormalDrawable(), gyBottomBarBean.getSelectDrawable(), tabImageWidthPx, tabImageHeightPx).toView()
                                    , gyTextView);
                    break;
                case TabShowType.HORIZONTAL_TEXT_IMAGE:
                    gyLinearLayout.getViewSet().setOrientation(LinearLayout.HORIZONTAL)
                            .addViews(gyTextView.getViewSet().setText(gyBottomBarBean.getTitle()).toView(),
                                    gyImageView.getViewSet().setTransformImages(gyBottomBarBean.getNormalDrawable(), gyBottomBarBean.getSelectDrawable(), tabImageWidthPx, tabImageHeightPx).toView()
                                            .getViewSet().setMarginPx(0, tabTextImageSpacingPx, 0, 0).toView());
                    break;
                case TabShowType.IMAGE:
                    gyLinearLayout.getViewSet().setOrientation(LinearLayout.VERTICAL)
                            .addViews(gyImageView.getViewSet().setTransformImages(gyBottomBarBean.getNormalDrawable(), gyBottomBarBean.getSelectDrawable(), tabImageWidthPx, tabImageHeightPx).toView());
                    break;
                case TabShowType.TEXT:
                    gyLinearLayout.getViewSet().setOrientation(LinearLayout.VERTICAL)
                            .setWidthPx(MATCH_PARENT)
                            .addViews(gyTextView.getViewSet().setText(gyBottomBarBean.getTitle()).toView());
                    break;
            }
            fragmentList.add(gyBottomBarBean.getFragment());
        }
//        gyFragmentPagerAdapter.notifyDataSetChanged();
        if (gyFragmentPagerAdapter != null) {
            gyFragmentPagerAdapter.notifyDataSetChanged();
        }
        setTabSelect(bottomBarViewPager.getCurrentItem());
    }

    public void build(FragmentManager fragmentManager) {
        gyFragmentPagerAdapter = new GYFragmentPagerAdapter(fragmentManager, fragmentList);
        bottomBarViewPager.setAdapter(gyFragmentPagerAdapter);
    }

    private int offsetHalfColor(float positionOffset, int offsetHalfColor, int normalColor) {
        if (positionOffset >= 0.5) {
            return offsetHalfColor;
        } else {
            return normalColor;
        }
    }

    private int offsetHalfTransform(float positionOffset, int offsetHalfTransform, int normalTransform) {
        if (positionOffset >= 0.5) {
            return offsetHalfTransform;
        } else {
            return normalTransform;
        }
    }

    private void setTabGradualChange(int position, float positionOffset) {
        ArgbEvaluator mainArgbEvaluator = new ArgbEvaluator();  // 根据偏移量 来得到
        int nowColor = (int) mainArgbEvaluator.evaluate(positionOffset, tabTextSelectColor, tabTextNormalColor);//当前tab的颜色值
        int toColor = (int) mainArgbEvaluator.evaluate(positionOffset, tabTextNormalColor, tabTextSelectColor);// 将要到tab的颜色值
        int noColor = (int) mainArgbEvaluator.evaluate(0, tabTextNormalColor, tabTextSelectColor);// tab未选中时的颜色值
        for (int i = 0; i < bottomBarLL.getViewSet().getChildViews().size(); i++) {
            if (i == position) {
                setTabTextViewColor(getTabTextView(position), tabShowAnimation ? nowColor : offsetHalfColor(positionOffset, tabTextNormalColor, tabTextSelectColor));
                setTabImageTransform(getTabImageView(position), tabShowAnimation ? (1 - positionOffset) : offsetHalfTransform(positionOffset, 0, 1));
                if (position < bottomBarLL.getViewSet().getChildViews().size() - 1) {
                    setTabTextViewColor(getTabTextView(position + 1), tabShowAnimation ? toColor : offsetHalfColor(positionOffset, tabTextSelectColor, tabTextNormalColor));
                    setTabImageTransform(getTabImageView(position + 1), tabShowAnimation ? positionOffset : offsetHalfTransform(positionOffset, 1, 0));
                }
            } else {
                if (i != position + 1) {
                    setTabTextViewColor(getTabTextView(i), noColor);
                    setTabImageTransform(getTabImageView(i), 0);
                }
            }
//            if (!tabShowPass && i != clickPosition && position != i && position != i - 1 && position != i + 1 && isClick) {//路径tab
//                setTabTextViewColor(getTabTextView(i), noColor);
//                setTabImageTransform(getTabImageView(i), 0);
//            }
            if (!tabShowPass && i != clickPosition && i != nowPosition && isClick) {//路径tab
                setTabTextViewColor(getTabTextView(i), noColor);
                setTabImageTransform(getTabImageView(i), 0);
            }
        }
    }

    private void setTabTextViewColor(GYTextView gyTextView, int color) {
        if (gyTextView != null) {
            gyTextView.getViewSet().setTextColor(color);
        }
    }

    private void setTabImageTransform(GYImageView gyImageView, float offset) {
        if (gyImageView != null) {
            gyImageView.getViewSet().setTransform(offset);
        }
    }

    private GYTextView getTabTextView(int position) {
        for (View view : getTabViews(position)) {
            if (view instanceof GYTextView) {
                return (GYTextView) view;
            }
        }
        return null;
    }

    private GYImageView getTabImageView(int position) {
        for (View view : getTabViews(position)) {
            if (view instanceof GYImageView) {
                return (GYImageView) view;
            }
        }
        return null;
    }

    private List<View> getTabViews(int position) {
        return ((GYLinearLayout) bottomBarLL.getViewSet().getChildViews().get(position)).getViewSet().getChildViews();
    }

    public GYViewPager getBottomBarViewPager() {
        return bottomBarViewPager;
    }
}
